package top.xianggg.xservers.sys.action;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.web.bind.annotation.*;
import top.xianggg.xservers.common.base.pojo.Result;

/**
 * @author Xiang
 */
@Api(tags = "用户登录")
@RestController
public class LoginController {

    /**
     * 登录接口， 由于前后分离，必须要自己处理登录
     * IMPORTANT 前端传入的密码进行初次加密，方式为md5，盐为用户名
     */
    @ApiOperation(value = "登录接口")
    @RequestMapping(value = "login",method = {RequestMethod.GET,RequestMethod.POST})
    public Result login(String username, String password, @RequestParam(required = false,defaultValue = "false") boolean remember) {
        // 手动处理登录
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(username,password,remember);
        // 登录失败从request中获取shiro处理的异常信息。
        // shiroLoginFailure:就是shiro异常类的全类名.
        Result result = Result.error(Result.ResultCode.loginFail);
        String msg;
        try {
            subject.login(token);
            if(remember){
                // 记住我的超期时间设为30天
                subject.getSession().setTimeout(1000*60*60*24*30L);
            }else{
                // 其余超期时间为2小时
                subject.getSession().setTimeout(1000*60*60*2L);
            }
            // 没错误登录返回
            return Result.success(subject.getSession().getId());
        } catch (IncorrectCredentialsException e) {
            msg = "密码错误";
        } catch (LockedAccountException e) {
            msg = "登录失败，该用户已被冻结";
        } catch (AuthenticationException e) {
            msg = e.getMessage();
        } catch (Exception e) {
            msg = "发生未知错误";
        }
        result.setMsg(msg);
        return result;
    }

    /**
     * 未登录，shiro应重定向到登录界面，此处返回未登录状态信息由前端控制跳转页面
     */
    @ApiOperation(value="获取用户信息")
    @GetMapping("unauthorized")
    public Result unauthorized(){
        return Result.error(Result.ResultCode.unauthorized);
    }

}